from urllib import response

from bs4 import BeautifulSoup
# from corsheaders.conf import conf
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import json
# Create your views here.
from django.http import  HttpResponse, HttpResponseRedirect

def index(request):
    return HttpResponseRedirect('/static/index.html')

def index1(request):
    import requests
    from bs4 import BeautifulSoup
    url = 'https://sinanews.sina.cn/h5/top_news_list.d.html'
    res = requests.get(url,'utf8')
    res.encoding = 'UTF-8'
    result = res.text
    soup = BeautifulSoup(result,'lxml')
    result = soup.find_all('script')[2].text
    index = result.find('{')
    end = result.find(';')
    data = json.loads(result[index:end])
    data = json.dumps(data['data'],ensure_ascii=False)
    print(data)
    return HttpResponse(data)

def article(request):
    import requests
    import re
    from bs4 import BeautifulSoup
    print(request.method)
    if request.method == 'POST':
        href = request.POST.get('link')
        print(href)
        res = requests.get(href, 'utf8')
        res.encoding = 'UTF-8'
        result = res.text
        soup = BeautifulSoup(result, 'lxml').find_all("script")
        for i in range(0, len(soup)):
            if "window.SM" in soup[i].text[0:]:
                result = soup[i].text

        index = result.find("window.SM")
        result = result[index+12:-1]

        data = json.loads(result)
        data = json.dumps(data,ensure_ascii=False)
        print(data)
        return HttpResponse(result)
    return HttpResponse("请点击链接进来")

def article_all(request):
    import requests
    import json
    from bs4 import BeautifulSoup
    if request.method == 'POST':
        print(request.POST)
        url = request.POST.get('link')
        res = requests.get(url, 'utf8')
        res.encoding = 'UTF-8'
        result = res.text
        soup = BeautifulSoup(result, 'lxml').find("article")
        title = soup.find("h1","art_tit_h1").text
        mean = soup.find_all("p")
        imges = soup.find_all("img","art_img_mini_img")
        list1 = []
        for i in imges:
            list1.append(i['data-src'])
        list = []
        for i in mean:
            list.append(i.text)
        result = {
            "images":list1,
            "title":title,
            "data":list,

        }
        print(result)
        result = json.dumps(result,ensure_ascii=False)

        return HttpResponse(result)
    return 0